package com.twopai.framelibrary.mvp;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import androidx.lifecycle.Lifecycle;

import com.twopai.comm.progressdialog.KProgressHUD;
import com.twopai.mvpbase.BasePresenter;
import com.twopai.mvpbase.BaseView;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.AutoDisposeConverter;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

/**
 * @author twopai
 * Description：
 */
public abstract class BaseMvpFragment<T extends BasePresenter>  extends BaseFragment implements BaseView {

    protected T mPresenter;

    private KProgressHUD progressBar;


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        super.onDestroyView();
        if(progressBar != null) {
            progressBar.dismiss();
        }
    }

    public void showToast(Context context, String msg){
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    public KProgressHUD showProgress(String msg){
        Log.e("BaseHelper","showProgress");
        if (progressBar != null) {
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
            progressBar=null;
        }
        progressBar = KProgressHUD.create(getActivity())
                .setDimAmount(0.5f)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setCancellable(true);
        if (msg != null&&!msg.isEmpty()) {
            progressBar.setLabel(msg);
        }
        progressBar.show();
        return progressBar;
    }

    public KProgressHUD showProgress(String msg,String etailsdMsg){
        Log.e("BaseHelper","showProgress");
        if (progressBar != null) {
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
            progressBar=null;
        }
        progressBar = KProgressHUD.create(getActivity())
                .setDimAmount(0.5f)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setCancellable(true);
        if (msg != null&&!msg.isEmpty()) {
            progressBar.setLabel(msg);
        }
        if (etailsdMsg != null&&!etailsdMsg.isEmpty()) {
            progressBar.setDetailsLabel(etailsdMsg);
        }
        progressBar.show();
        return progressBar;
    }
    public void dismissProgress(){
        if (progressBar != null) {
            progressBar.dismiss();
            progressBar=null;
        }
        Log.e("BaseHelper","dismissProgress");
    }


    /**
     * //开始只在activity中才有，2019.2.12添加
     * 绑定生命周期 防止MVP内存泄漏
     *
     * @param <T>
     * @return
     */
    @Override
    public <T> AutoDisposeConverter<T> bindAutoDispose() {
        return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider
                .from(this, Lifecycle.Event.ON_DESTROY));
    }
}
